import React, {useRef, useEffect, useState} from "react";
import {getSrc} from "./helpers/phonics-helper";

const synth = window.speechSynthesis;
var msg = new SpeechSynthesisUtterance();

export function Player(props) {
    const {queue} = props;
    const voices = speechSynthesis.getVoices().filter(v=>v.lang.includes('en') && v.localService);

    const ref = useRef();
    const playRef = useRef();
    // const [playing, togglePlaying] = useReducer(v => !v, false);
    const [prev, setPrev] = useState('');
    const [index, setIndex] = useState(0);


    const playSound = (phonics) => {
        synth.cancel();
        msg.text = phonics;
        msg.voice = voices[Math.floor(Math.random()*voices.length)];
        synth.speak(msg);

        // ref.current.src = getSrc(phonics);
        // ref.current.play();
    };


    useEffect(() => {
        playRef.current = () => {
            if (index + 1 < queue.length) {
                setIndex(index + 1);
                // if(['j', 'q', 'x', 'y'].includes(prev) && queue[index+1].startsWith('u')) {
                //     console.log(`last: ${prev}, current: ${queue[index + 1]} change to: ${queue[index + 1].replace('u', 'v')}`)
                //     playSound(queue[index + 1].replace('u', 'v'));
                // } else {
                //     playSound(queue[index + 1]);
                // }
                playSound(queue[index + 1]);

                setPrev(queue[index + 1]);
            }
        };
    });

    useEffect(() => {
        // ref.current.addEventListener('play', () => {
        //     togglePlaying();
        // });
        // ref.current.addEventListener('pause', () => {
        //     togglePlaying();
        // });
        function getRefValue() {
            playRef.current();
        }
        ref.current.addEventListener('ended', getRefValue);
    }, []);


    useEffect(() => {
        setIndex(0);
        if(!ref.current.paused) {
            ref.current.pause();
        }
        if (queue.length > 0) {
            setPrev(queue[0]);
            playSound(queue[0])
        }
    }, [queue]);

    return <>
        <audio ref={ref}/>
    </>
}
